package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private IWemediaClient iWemediaClient;
    @Autowired
    private CacheService cacheService;

    /**
     * 定时计算热点文章
     */
    @Override
    public void computeHotArticle() {

        //查询前5天发布的文章
        Date date = DateTime.now().minusDays(5).toDate();
        List<ApArticle> list = apArticleMapper.findArticleListByDays(date);

        //计算文章分值
        if (null != list && list.size() > 0) {
            List<HotArticleVo> voList = computeHotArticleScore(list);
            //给每个频道缓存30条分值较高的文章,把数据缓存到redis
            cacheTagToRedis(voList);
        }

    }

    //缓存数据到每一个频道和推荐
    private void cacheTagToRedis(List<HotArticleVo> voList) {
        //1. 缓存每个频道的数据
        //1.1 查询所有的频道
        ResponseResult responseResult = iWemediaClient.findAll();
        if (null != responseResult && responseResult.getCode() == 200) {
            if (null != responseResult.getData()) {
                //1.2 遍历所有的频道并查询当前遍历频道的所有的文章->排序 -> 获取得分最高的30行记录
                String json = JSON.toJSONString(responseResult.getData());
                List<WmChannel> channelList = JSON.parseArray(json, WmChannel.class);

                for (WmChannel channel : channelList) { //遍历一个频道出来
                    List<HotArticleVo> list = voList.stream().filter(item -> channel.getId().equals(item.getChannelId())) //每个文章对应的频道id
                            //排序规则Comparator.comparing
                            .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                            .limit(30)
                            .collect(Collectors.toList());

                    //1.3 把获取的30行记录存储到redis里面-key: 前缀+频道id,value: json(30行记录)
                    cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + channel.getId(),JSON.toJSONString(list));
                }
            }
            // 添加推荐的数据
            List<HotArticleVo> list = voList.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .limit(30)
                    .collect(Collectors.toList());
            cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG, JSON.toJSONString(list));

        }

    }

    //计算所有文章得分
    private List<HotArticleVo> computeHotArticleScore(List<ApArticle> list) {
        List<HotArticleVo> voList = new ArrayList<>(list.size());
        for (ApArticle article : list) {
            HotArticleVo vo = new HotArticleVo();
            BeanUtils.copyProperties(article, vo);
            vo.setScore(computeScore(article));
            voList.add(vo);
        }

        return voList;
    }

    //计算一篇文章的得分

    /**
     * 阅读权重：1   点赞权重：3  评论权重：5  收藏权重：8
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if (null != apArticle.getViews()) {
            score += apArticle.getViews();
        }

        if (null != apArticle.getLikes()) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (null != apArticle.getComment()) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (null != apArticle.getCollection()) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
